package com.microblogforsim.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.lzy.okgo.OkGo;
import com.microblogforsim.R;
import com.microblogforsim.activity.LoginActivity;
import com.microblogforsim.activity.PreviewImgActivity;
import com.microblogforsim.adapter.UserHistoryAdapter;
import com.microblogforsim.adapter.UserMenuAdapter;
import com.microblogforsim.callback.JsonCallback;
import com.microblogforsim.model.LzyResponse;
import com.microblogforsim.model.Topics;
import com.microblogforsim.model.User;
import com.microblogforsim.model.User_History_Item;
import com.microblogforsim.model.User_Menu_Item;
import com.microblogforsim.utils.ACache;
import com.microblogforsim.utils.Urls;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class Fragment_User extends Fragment implements View.OnClickListener {
    private View view;
    private Button btn_get;
    private TextView textView;



    private static final int GET = 1;
    String TAG = "tag";
    //缓存
    private ACache mCache;
    private SharedPreferences sharedPreferences;

    //退出登录
    private Button btn_logout;

    //    简介区
    private ImageView iv_info_upic, iv_info_vip;
    private TextView tv_info_uname, tv_info_info, tv_info_member;
    private View v_newPoint;
    //    简介统计
    private LinearLayout btn_weibo, btn_guangzhu, btn_fans, ly_infoCot, ly_my_record, ly_ad;
    private TextView tv_num_weibo, tv_num_guangzhu, tv_num_fans;
    //    菜单列表
    private GridView l_menu;
    //    浏览历史
    private TextView btn_cheakMore;
    private GridView l_history_list;
    //    广告
    private ImageView iv_ad;
    //    菜单数据源
    private ArrayList<User_Menu_Item> menu_items;
    //    菜单适配器
    private UserMenuAdapter menuAdapter;
    //    浏览历史列表数据源
    private ArrayList<User_History_Item> history_items;
    //    浏览历史列表适配器
    private UserHistoryAdapter historyAdapter;
    //    
    private String openid = "";


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(Message message) {
            super.handleMessage(message);
            switch (message.what) {
                case GET:
                    textView.setText((String) message.obj);
                    break;

            }
        }
    };


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_user, container, false);
        init();
        return view;
    }

    /**
     * 将用户信息设置到视图上
     */
    private void set_info(User user) {

        if (user != null) {
            tv_info_uname.setText(user.getUserName());
            tv_info_info.setText("简介：" + user.getSign());
            tv_num_guangzhu.setText(user.getLike() + "");
            tv_num_fans.setText(user.getLiked() + "");
            //使用Glide加载图片
            Glide.with(getContext())
                    //加载地址
                    .load(user.getImg())
                    //加载失败时，设置默认的图片
                    .placeholder(R.drawable.loading)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    //显示的位置
                    .into(iv_info_upic);
        } else {
            Toast.makeText(getContext(), "user null", Toast.LENGTH_SHORT).show();
           // get_user_info();
        }
    }

    /**
     * 初始化组件
     */
    private void init() {
//        简介区
        iv_info_upic = view.findViewById(R.id.fragment_user_info_upic);
        tv_info_uname = view.findViewById(R.id.fragment_user_info_uname);
        tv_info_info = view.findViewById(R.id.fragment_user_info_info);
        iv_info_vip = view.findViewById(R.id.fragment_user_info_vipImg);
        tv_info_member = view.findViewById(R.id.fragment_user_info_member);
        v_newPoint = view.findViewById(R.id.fragment_user_info_member_new);
//        简介统计
        ly_infoCot = view.findViewById(R.id.ly_infoCot);
        btn_weibo = view.findViewById(R.id.btn_infoCot_weibo);
        btn_guangzhu = view.findViewById(R.id.btn_infoCot_guangzhu);
        btn_fans = view.findViewById(R.id.btn_infoCot_fans);
        tv_num_weibo = view.findViewById(R.id.fragment_user_infoCot_weibo);
        tv_num_guangzhu = view.findViewById(R.id.fragment_user_infoCot_guangzhu);
        tv_num_fans = view.findViewById(R.id.fragment_user_infoCot_fans);
//        菜单列表
        l_menu = view.findViewById(R.id.fragment_user_menu_list);
//        浏览历史
        ly_my_record = view.findViewById(R.id.ly_my_record);
        btn_cheakMore = view.findViewById(R.id.fragment_user_history_all);
        l_history_list = view.findViewById(R.id.fragment_user_history_list);
//         广告
        ly_ad = view.findViewById(R.id.ly_ad);
        iv_ad = view.findViewById(R.id.fragment_user_ad_img);
        //logout
        btn_logout = view.findViewById(R.id.fragment_user_logout);

//        点击事件监听
        btn_logout.setOnClickListener(this);
        iv_info_upic.setOnClickListener(this);
        tv_info_member.setOnClickListener(this);
        btn_weibo.setOnClickListener(this);
        btn_guangzhu.setOnClickListener(this);
        btn_fans.setOnClickListener(this);
        btn_cheakMore.setOnClickListener(this);
        iv_ad.setOnClickListener(this);
        tv_info_uname.setOnClickListener(this);
        menu_items = new ArrayList<>();
        history_items = new ArrayList<>();
        mCache = ACache.get(getContext());
        sharedPreferences = getContext().getSharedPreferences("data", Context.MODE_PRIVATE);

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
//            更新数据
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        openid = sharedPreferences.getString("openid", "");
       

        if (openid.equals("")) {
            ly_infoCot.setVisibility(View.GONE);
            ly_my_record.setVisibility(View.GONE);
            ly_ad.setVisibility(View.GONE);
            btn_logout.setEnabled(false);
            tv_info_uname.setText("登录/注册");
            tv_info_info.setText("");
            iv_info_upic.setImageResource(R.drawable.shuai);
            menu_items.clear();
        } else {
            btn_logout.setEnabled(true);
            ly_infoCot.setVisibility(View.VISIBLE);
            ly_my_record.setVisibility(View.VISIBLE);
            ly_ad.setVisibility(View.VISIBLE);
          User  userinfo = (User) mCache.getAsObject("UserInfo");
          if(userinfo!=null){
              set_info(userinfo);
          }
            get_user_info(openid);
            setMenuList();
            setHistoryList();
        }
    }

    /**
     * 获取用户信息
     */
    private void get_user_info(final String id) {
        OkGo.<LzyResponse<User>>post(Urls.SERVER + "User/getByOpenid")//
                .tag(this)//
                .headers("header1", "headerValue1")//
                .params("openid", id)//
                .execute(new JsonCallback<LzyResponse<User>>() {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<LzyResponse<User>> response) {
                        // handleResponse(response);
                        Log.d("get_user_info", id+"onSuccess: " +( response.body().data==null));

                        if (response.body().msg.equals("success")) {
                           User user = response.body().data;
                            if(user!=null){
                                set_info(user);
                                mCache.put("UserInfo", user);
                            }
                        }else {
                            Toast.makeText(getContext(), "获取用户信息失败"+response.body().data.toString(), Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<LzyResponse<User>> response) {
                        // handleError(response);
                        Toast.makeText(getContext(), "网络出错", Toast.LENGTH_SHORT).show();
                    }
                });

    }

    private void setMenuList() {
        menu_items.add(new User_Menu_Item(R.drawable.ic_tupian_user_menu, "我的相册", false));
        menu_items.add(new User_Menu_Item(R.drawable.ic_dianzan_user_menu, "赞/收藏", false));
        menu_items.add(new User_Menu_Item(R.drawable.ic_liulanlishi, "浏览记录", false));
        menu_items.add(new User_Menu_Item(R.drawable.ic_caogao, "草稿箱", false));
        menu_items.add(new User_Menu_Item(R.drawable.ic_qianbao, "我的钱包", true));
        menu_items.add(new User_Menu_Item(R.drawable.ic_dianying, "创作中心", false));
        menu_items.add(new User_Menu_Item(R.drawable.ic_icon_fans_top, "粉丝头条", false));
        menu_items.add(new User_Menu_Item(R.drawable.ic_kefu, "客服", false));
        menuAdapter = new UserMenuAdapter(getContext(), menu_items);
        l_menu.setAdapter(menuAdapter);
        l_menu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    default:
                        Toast.makeText(getContext(), position + "menu", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void setHistoryList() {
        for (int i = 0; i < 5; i++) {
            history_items.add(new User_History_Item(R.drawable.shuai, "衰神"));
        }
        int size = history_items.size();

        int length = 74;

        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int gridviewWidth = (int) (size * (length + 4) * density);
        int itemWidth = (int) (length * density);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.MATCH_PARENT);
        l_history_list.setLayoutParams(params);
        l_history_list.setColumnWidth(itemWidth);
        l_history_list.setHorizontalSpacing(5);
        l_history_list.setStretchMode(GridView.NO_STRETCH);
        l_history_list.setNumColumns(size);

        historyAdapter = new UserHistoryAdapter(getContext(), history_items);
        l_history_list.setAdapter(historyAdapter);
        l_history_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    default:
                        Toast.makeText(getContext(), position + "history", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fragment_user_info_upic:
                Toast.makeText(getContext(), "点击了头像", Toast.LENGTH_SHORT).show();
                break;
            case R.id.fragment_user_info_member:
                Toast.makeText(getContext(), "点击了会员", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_infoCot_weibo:
                Toast.makeText(getContext(), "点击了微博", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_infoCot_guangzhu:
                Toast.makeText(getContext(), "点击了关注", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_infoCot_fans:
                Toast.makeText(getContext(), "点击了粉丝", Toast.LENGTH_SHORT).show();
                break;
            case R.id.fragment_user_history_all:
                Toast.makeText(getContext(), "点击了查看更多", Toast.LENGTH_SHORT).show();
                break;
            case R.id.fragment_user_ad_img:
//                Intent intent1 = new Intent(getContext(), PreviewImgActivity.class);
//                getContext().startActivity(intent1);
                Toast.makeText(getContext(), "点击了广告图片", Toast.LENGTH_SHORT).show();
                break;
            case R.id.fragment_user_info_uname:
                if (openid.equals("")) {
                    Intent intent = new Intent(getContext(), LoginActivity.class);
                    getActivity().startActivity(intent);
                }
                break;
            case R.id.fragment_user_logout:
                if (!openid.equals("")) {
                    Toast.makeText(getContext(), "退出登录", Toast.LENGTH_SHORT).show();
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.remove("openid");
                    openid = "";
                    editor.commit();
                    menu_items.clear();
                    mCache.remove("UserInfo");
                    this.onResume();
                } else {
                    Toast.makeText(getContext(), "请登录", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }



}
